﻿using System;
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
using SimulationCenter.Models;
using SimulationCenter.Scripts;
using SimulationCenter.Tasks.Svrs;

namespace SimulationCenter
{
    public class AdbHub : Hub
    {
        private readonly AdbCenter _adbCenter;
        private readonly ScriptManager _scriptManager;
        private readonly ISubscriptionSvr _subscriptionSvr;

        public AdbHub(AdbCenter adbCenter, ScriptManager scriptManager, ISubscriptionSvr subscriptionSvr)
        {
            _adbCenter = adbCenter;
            _scriptManager = scriptManager;
            _subscriptionSvr = subscriptionSvr;
        }

        /// <summary>
        /// 获取 adb 服务器状态
        /// </summary>
        /// <returns></returns>
        public async Task GetStatus()
        {
            await Clients.Caller.SendAsync("status", _adbCenter.GetStatus());
        }

        /// <summary>
        /// 获取在线设备列表
        /// </summary>
        /// <returns></returns>
        public async Task GetDevices()
        {
            await Clients.Caller.SendAsync("devices", _adbCenter.GetDevices());
        }

        /// <summary>
        /// 指定设备执行脚本
        /// </summary>
        /// <param name="serial"></param>
        public void ExecuteScript(string serial)
        {
            _scriptManager.Execute(serial);
        }

        /// <summary>
        /// 指示公众号检索完毕
        /// </summary>
        /// <param name="subscription"></param>
        public async Task CompleteSubscription(string subscription)
        {
            await _scriptManager.CompleteDeviceTask(subscription);
        }

        /// <summary>
        /// 获取公众号检索范围
        /// </summary>
        /// <param name="subscription"></param>
        /// <returns></returns>
        public async Task GetFetchMsgsRange(string subscription)
        {
            Resp resp;

            try
            {
                var msgsRange = await _subscriptionSvr.GetFetchMsgsRange(subscription);
                resp = Resp.Success(msgsRange);
            }
            catch (Exception e)
            {
                resp = Resp.Failure(e);
            }

            await Clients.Caller.SendAsync("msgsRange", resp);
        }
    }
}
